import {app, BrowserWindow, ipcMain, session,globalShortcut,dialog} from 'electron';

const config = require('../config/config');
const path = require('path');
import merchant from './merchant_v1'
import jsplugin from './jsPlugin'
import junglescout from './junglescout'
import aes from '../util/aes_util';
const cp = require('child_process');
const cookieBoj = {}, timeHeart={}

let isDev = process.env.NODE_ENV !== 'production';
let token = ''; //存储登录token 方便关闭时调用退出接口

let winCache = [];

const userName = process.env['USERPROFILE'].split(path.sep)[2];
console.log(`Current windows login userName:${userName}`);

global.baseResourcePath = isDev ?  path.resolve(__dirname,'../../extraResources/') : path.resolve(process.resourcesPath, 'extraResources/');
global.baseResourcePath = global.baseResourcePath.replace(/\\/g, '\\\\');
console.log(`baseResourcePath:${global.baseResourcePath}`);

const pluginPath = path.resolve(global.baseResourcePath,'jsPlugin');
const proxyPluginPath = path.resolve(global.baseResourcePath,'proxy');
const wyfyPluginPath = path.resolve(global.baseResourcePath,'wyfy');
const googlePluginPath = path.resolve(global.baseResourcePath,'google_fy');
const userDataPath = path.resolve(global.baseResourcePath,'User Data');
global.toolsPath    = path.resolve(global.baseResourcePath,'tools');

global.crtPath = global.toolsPath + '/' + config.SSL.NAME;
/**
 * 检查证书是否存在
 */
(async function (){
    let install2 = `${global.toolsPath}/certmgr.exe -add -c ${global.crtPath} -s -r localMachine Root`;
    try {
      let result = cp.execSync(install2).toString();
      console.log(`The certificate is installed ${result}`)
    } catch (e) {
      console.log(`The certificate installation failed, please restart. Message:${e}`)
    }

  // if(!await checkCertInstall()){
  //   app.quit();
  // }
})();

async function checkCertInstall(){
  let checkIsExist = `${global.toolsPath}/certmgr.exe -c ${global.crtPath}`;
  try {
    let result = cp.execSync(checkIsExist).toString();
    console.log(`Certificate check passed ${result}` );
    return true
  } catch (e) {
    console.log(`Check Certificate failed. message:${e}`);
    return false;
  }
}



// 引入api
import {heartbeat, resetSetCookie, logout} from '../request/ajax';

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';



if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`;

function createWindow(loadUlrJoy,isInject,height = 820,width = 1200) {
  let win;
  win = new BrowserWindow({
    height: height,
    useContentSize: true,
    width: width,
    icon: isDev ? path.join(__dirname, '../../extraResources/icons/icon.ico') : path.join(process.resourcesPath, 'extraResources/icons/icon.ico'),
    webPreferences: {
      nodeIntegration: true,
      webSecurity: false
    }
  });

  // win.webContents.openDevTools();

  //隐藏菜单栏
  win.removeMenu();
  //退出主程序，清除定时器
  win.on('closed', () => {
    console.log('closed')
    if(!loadUlrJoy || !loadUlrJoy.url){
      return;
    }
    winCache[loadUlrJoy.url] = null
    for (let key in timeHeart) {
      if(timeHeart.hasOwnProperty(key)) {
        clearInterval(timeHeart[key])
      }
    }
    // clearInterval(BrowserWindow.timeHeart) //退出主程序清除定时器
    win = null
  })
  win.loadURL(winURL);
  winCache['mainWindow'] = win;
  return win
}


ipcMain.on('news', function (e, msg) { //news 是自定义的命令 ，只要与页面发过来的命令名字统一就可以

  let {url, cookie, token, payload, userName, passWord, productUserId,loginUser,expireTime,productId} = msg
  let win, merchantWin,pluginWin, timer,junglescoutWin;
  console.log(`---------- msg:${JSON.stringify(msg)} \n userData:${userDataPath} `)
  // let isExistWin = winCache[url];
  // console.log(`---winCache------- cache:${isExistWin} `)
  // if(isExistWin){
  //   console.log(`重复创建 url:${url}`)
  //   let options = {
  //     type:'info',
  //     title:'警告',
  //     message:'请勿重复打开',
  //     buttons:['好的']
  //   }
  //   dialog.showMessageBox(options,(index) => {
  //     console.log(`click:${index}`)
  //   })
  //   return;
  // }
  cookieBoj[url] = cookie;
  if(url && url === 'https://www.merchantwords.com') {
    merchantWin = new merchant({
      token:token,
      targetUrl: url,
      productObj:msg,
      pluginPath:pluginPath,
      proxyPath:proxyPluginPath,
      wyfyPluginPath:wyfyPluginPath,
      googlePluginPath:googlePluginPath,
      bookmarkPath:userDataPath,
      basePath:baseResourcePath,
      closeFn: () => {
        winCache[url] = null;
        cookieBoj[url] = null;
        clearInterval(timeHeart[url]);
      }
    });
    merchantWin.loadWindow();
    winCache[url] = merchantWin;
  } else if(url && url === 'https://members.junglescout.com/'){
    junglescoutWin = new junglescout({
      token:token,
      targetUrl: url,
      productObj:msg,
      clientToken:token,
      productId:productId,
      pluginPath:pluginPath,
      proxyPath:proxyPluginPath,
      wyfyPluginPath:wyfyPluginPath,
      googlePluginPath:googlePluginPath,
      bookmarkPath:userDataPath,
      closeFn: () => {
        winCache[url] = null;
        cookieBoj[url] = null;
        clearInterval(timeHeart[url]);
      },clearCacheCookie: () => {
        cookieBoj[url] = null;
      },
      decode: (str) => {
        return aes.decode(str);
      }
    });
    junglescoutWin.loadWindow();
    winCache[url] = junglescoutWin;

  }else{
    pluginWin = new jsplugin({
      token:JSON.parse(cookie),
      pluginPath:pluginPath,
      proxyPath:proxyPluginPath,
      wyfyPluginPath:wyfyPluginPath,
      googlePluginPath:googlePluginPath,
      username:loginUser,
      expireTime:expireTime,
      productId:productId,
      clientToken:token,
      bookmarkPath:userDataPath,
      closeFn: () => {
        winCache[url] = null;
        cookieBoj[url] = null;
        clearInterval(timeHeart[url]);
      },
      decode: (str) => {
        return aes.decode(str);
      }
    });
    pluginWin.loadWindow();
    winCache[url] = pluginWin;
  }

  timeHeart[url] = setInterval(() => {
    heartbeat(payload, token).then(resp => {
      // if(!resp){
      //   return;
      // }
      // resp = aes.decode(resp)
      // resp = JSON.parse(resp);
    })
  }, 3000)
  //接收到消息后的执行程序
})

ipcMain.on('login', function (e, res) {
  console.log(res, 'login')
  token = res
})


const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
      mainWindow.show()
    }
  })
}

//禁用GPU加速 防止某些电脑白屏
app.disableHardwareAcceleration();

app.on('ready', () => {
  mainWindow = createWindow()
  mainWindow.on('close', async (e) => {
    e.preventDefault();
    if(token) {
      console.log(token)
      await logout(token)
    }
    app.exit();
  })
  globalShortcut.register('F5', () => {
    return false;
  });
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    mainWindow = createWindow()
  }
})

// app.on('window-all-closed', function () {
//     console.log('close')
// })

